import router from '@/router/index.ts'
import nprogress from 'nprogress'
import "nprogress/nprogress.css"
import pinia from '@/store'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore(pinia)
router.beforeEach(async (to: any, from: any, next: any) => {
    nprogress.start()
    const token = userStore.token
    const username = userStore.username
    if(token){
        if(to.path == '/login'){
            next("/home")
        }else{
            if(username){
                next()
            }else{  
                try {
                    await userStore.userInfo()
                    next({...to})
                } catch (error) {
                    await userStore.userLogout()
                    next('/login')
                } 
            }
        }
    }else{
        if(to.path == '/login'){
            next()
        }else{
            next('/login')
        }
    }
})

router.afterEach(() => {
    nprogress.done()
})